package io.terminus.spzx.user.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import io.terminus.spzx.common.config.exception.SpzxCustomException;
import io.terminus.spzx.consts.UserInfoConstant;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.user.service.SmsService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 阿里云SMS短信服务Service实现类
 * @Date 2024-11-16
 */
@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    private static final String product = "Dysmsapi";

    /**
     * 产品域名,开发者无需替换
     */
    private static final String domain = "dysmsapi.aliyuncs.com";

    static final String accessKeyId = "LTAI5tMT2kvPPho6yFssYu4M";

    static final String accessKeySecret = "vFZjMgIpE5CQJ6WtcAOTMsk6xal3Yx";

    @Override
    public void sendValidateCode(String phone) {
        String code = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_SMS_VALIDATE_CODE_KEY_PREFIX + phone);
        if (StringUtils.hasText(code)) {
            return;
        }

        // 生成验证码
        String validateCode = RandomStringUtils.randomNumeric(4);
        redisTemplate.opsForValue().set(UserInfoConstant.REDIS_SMS_VALIDATE_CODE_KEY_PREFIX + phone, validateCode, 5, TimeUnit.MINUTES);
        sendSms(phone, validateCode);
    }

    /**
     * 发送短信验证码
     *
     * @param phone        手机号
     * @param validateCode 验证码
     */
    public void sendSms(String phone, String validateCode) {
        // 设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        try {
            // 初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setSignName("个人学习自用");
            request.setTemplateCode("SMS_475285453");
            request.setTemplateParam("{\"code\":\"" + validateCode + "\"}");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                System.out.println("短信发送成功！");
            } else {
                System.out.println("短信发送失败：" + sendSmsResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SpzxCustomException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }

}
